from pyhildonmemer import commons

from pyhildonmemer.services import ServicesList

from meme import *
from tri_peh import TriPeh

class MemerRepository(MemeRepository):
    def __init__(self, yqlPrivate):
        self.syql = yqlPrivate
        super(MemerRepository, self).__init__()

    def _executeMeme(self, query):
        result = self.syql.execute(query)
        if result.count == 1:
            return [Meme(result.rows)]
        return [Meme(row) for row in result.rows]

    def _executePost(self, query):
        result = self.syql.execute(query)
        if result.count == 1:
            return [Post(result.rows)]
        return [Post(row) for row in result.rows]

    def getMyInfo(self):
        return self._executeMeme("select * from meme.info where owner_guid=me")

    def post(self, content):
        return self._executePost("insert into meme.user.posts (type, content" + content)

    def postMedia(self, tpe, content, caption = ""):
        return self.post(", caption) values (\""+ tpe + "\", \"" + content + "\", \"" + caption + "\")")

    def postText(self, content, caption):
        return self.postMedia("text", content, caption)

    def postVideo(self, content, caption = ""):
        return self.postMedia("video", content, caption)

    def postAudio(self, content, caption = ""):
        return self.postMedia("audio", content, caption)

    def postImage(self, content, caption = ""):
        return self.postMedia("photo", content, caption)

    def delete(self, pid):
        return self._executePost("delete from meme.user.posts where pubid = \"" + pid +"\"")

    def follow(self, uid):
        return self._executeMeme("insert into meme.user.following (guid) values (\""+ uid + "\")")

    def unfollow(self, uid):
        return self._executePost("delete from meme.user.posts where guid = \"" + uid + "\"")

    def comment(self, uid, pid, comment):
        return self.syql.execute("insert into meme.user.comments (guid, pubid, comment) values (\""+uid+"\",\""+pid+"\",\""+comment+"\")")

    def repost(self, uid, pid, comment):
        return self._executePost("insert into meme.user.posts (guid, pubid, comment) values (\""+uid+"\",\""+pid+"\",\""+comment+"\")")

    def getDashBoard(self):
        return self._executePost("select * from meme.user.dashboard")

    def syqlExecute(self, query, param):
        return self.syql.execute(query, param)

class MemerService(commons.ServiceOauth):
    def __init__(self):
        self.yql = TriPeh()
        self.repository = None
        self.posts = PostRepository()
        self.memes = MemeRepository()
        super(ServiceOauth, self).__init__()

    def __init__(self):
        return "MemerService"

    @staticmethod
    def getServiceId():
        """Retun class name"""
        return "hildonmemer.services.memer"

    @staticmethod
    def getHowImport():
        """Return import sintax"""
        raise "from pyhildonmemer.services import memer"


    def getAuthUrl(self):
        self.authUrl = self.yql.getYuri()
        return self.authUrl

    def setToken(self, token):
        self.token = token
        self.yql.setUleg(self.token)
        self.repository = MemerRepository(self.yql)

    def setAccessToken(self, token):
        self.yql.setAccessToken(token)

    def getAccessToken(self, token = None):
        if not(token == None):
            self.setToken(token)
        return self.yql.getAccessToken()

    def getMemesRepository(self):
        return self.memes

    def getPostsRepository(self):
        return self.posts

    def getMemerRepository(self):
        return self.repository

    def getProfileService(self):
        return MemerProfileService(self)

    def getPostService(self):
        pass

class MemerProfileService(commons.ProfileService):
    def __init__(self, memer):
        self.memer = memer
        me = memer.getMemerRepository().getMyInfo()
        super(MemerProfileService, self).__init__(MemerProfile.memeToProfile(me))

class MemerProfile(commons.Profile):
    def memeToPrifle(meme):
        return commons.Profile(meme.guid, meme.name, meme.title, meme.description, meme.avatar)

class MemerPost(commons.Post):
    def memeToPost(post):
        postype = None
        if post.type == "photo":
            postype = commons.Post.TYPE_IMAGE
        elif post.type == "video":
            postype = commons.Post.TYPE_VIDEO
        elif post.type == "audio":
            postype = commons.Post.TYPE_AUDIO
        else:
            postype = commons.Post.TYPE_TEXT
        return commons.Post(post.pubid, post.guid, post.content, post.caption, postype, post.url)

class MemerPostService(commons.PostService):
    def __init__(self, memer):
        self.memer = memer

    def postIt(self, post):
        if type(post.content) == type("") and not(regex.match("^http://", post.content)):
            raise NotImplementedError()
        if post.getPostType == commons.Post.TYPE_IMAGE:
            self.memer.getRepository().postImage(post.content, post.caption)
        elif post.getPostType == commons.Post.TYPE_VIDEO:
            self.memer.getRepository().postVideo(post.content, post.caption)
        elif post.getPostType == commons.Post.TYPE_AUDIO:
            self.memer.getRepository().postAudio(post.content, post.caption)
        else:
            self.memer.getRepository().postText(content, caption)

    def delPost(self, post):
        self.memer.getRepository().delete(post.pid);

    def search(self, query, limit = 5, page = 1):
        posts = self.memer.getPostsRepository().search(query, page)
        return [ MemerPost.memeToPost(post) for post in posts]

    def dashBoard(self):
        posts = self.memer.getPostsRepository().getDashBoard()
        return [MemerPost.memeToPost(post) for post in posts]


"""
    Add to service list
"""
ServicesList.add(MemerService)